/*
 * Copyright 2002-2004 The Apache Software Foundation.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.nanhill.commons.id.task;

import static org.nanhill.commons.id.uuid.Constants.MD5_ENCODING;
import static org.nanhill.commons.id.uuid.Constants.SHA1_ENCODING;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.nanhill.commons.id.IdentifierUtils;
import org.nanhill.commons.id.uuid.UUID;
/**
 * Simple Ant task to generate a UUID.
 * $Id: UUIDTask.java,v 1.1 2006/09/20 06:56:00 alin Exp $
 */
public class UUIDAntTask extends Task {
	
	private String uuidVersion = "VERSION_FOUR";
	private String name = "www.apache.org";
	private String namespace = "urn:uuid:B4F00409-CEF8-4822-802C-DEB20704C365";
	
	public void setName(String name) {
		this.name = name;
	}
	
	public void setNamespace(String namespace) {
		this.namespace = namespace;
	}
	
	public static class UUIDVersion extends EnumeratedAttribute {
		public String[] getValues() {
			return new String[] { "VERSION_ONE", "VERSION_THREE", "VERSION_FOUR", "VERSION_FIVE" };
		}
	}
	
	public void setVersion(UUIDVersion newVersion) {
		uuidVersion = newVersion.getValue();
	}
	
	public void execute() throws BuildException {
		UUID uuid = null;
		if (uuidVersion.equals("VERSION_THREE")) {
			uuid = UUID.nameUUIDFromString(name, new UUID(namespace), MD5_ENCODING);
		}
		else if (uuidVersion.equals("VERSION_FIVE")) {
			uuid = UUID.nameUUIDFromString(name, new UUID(namespace), SHA1_ENCODING);
		}
		else if (uuidVersion.equals("VERSION_FOUR")) {
			uuid = (UUID) IdentifierUtils.UUID_VERSION_FOUR_GENERATOR.nextIdentifier();
		}
		else if (uuidVersion.equals("VERSION_ONE")) {
			uuid = UUID.timeUUID();
		}
		
		setProperty("uuid", uuid.toString());
	}
	
	private void setProperty(String name, String value) {
        getProject().setProperty(name, value);
    }
	
}
